import React, { useEffect } from 'react'
import { useNavigate } from 'react-router'

import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Form, Input } from 'antd'

import './index.scss'

import { userLogin } from '@/api/home'
import { setToken, getToken } from '@/utils/setToken'
const Login: React.FC = () => {
  const navigate = useNavigate()

  const onFinish = async (values: unknown) => {
    const res = await userLogin(
      values as { userName: string; password: string }
    )
    setToken(res.data.token)
    navigate('/', { replace: true })
  }

  useEffect(() => {
    if (getToken()) {
      navigate('/', { replace: true })
    }
  }, [])

  return (
    <div className="login-view">
      <div className="input-box">
        <div className="title">系统登录</div>
        <Form onFinish={onFinish}>
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="Username" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item>
            <Button block type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
